<template>
  <!-- 新增 搜索 -->
  <div>
    <!-- 表单 -->
    <TopFilter ref="form" :cols="3" :list="list" :isSubmitBtn="true" :collapse="true" @filterChange="formChange"></TopFilter>
    <!-- 表格 -->
    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="partPartInventoryPartInventoryComponentsSearchPart"
      :fetchapi="fetchApi"
      :params="fetchParams"
      height="auto"
      selectionType="single"
      :datakey="'rows'"
      :onCellChange="cellChangeHanle"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="handleTableRowSelectChange"
      :onPageChange="onPageChange"
      :onEnterEvent="onEnterEvent"
      :rowstyles="styleList"
      :onSyncTableData="syncDataChange"
    ></FilterTable>
  </div>
</template>

<script>
import SERVER from '@/api/server';
import { dictionary } from '@/utils/dictMixin';
import { isAuthorized } from '@/utils/index';
import axios from '@/api/fetch';
import { state, mutations } from '@/store';
import { queryPartStock } from '@/api/part/partOutbound/repairMaterials/index.js';
import { getBrand } from '@/api/repair/basicParameters';
import { findAllRepair } from '@/api/repair/basicParameters';
import { queryTex, queryPartinventoryPrintParam } from '@/api/part/common';
import { getCangKuSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';

export default {
  name: 'cgrk_part_search',
  mixins: [dictionary],
  props: {
    type: String, // add（手工入库） 与非 add
    ptype: String // 模块区分
  },
  data() {
    return {
      onChangeColumn: [],
      list: this.createList(),
      pj: false,
      columns: this.createColumns(),
      fetchApi: this.queryPartInfo,
      styleList: [],
      cunTax: '',
      tax: '',
      fetchParams: { xhrAbort: true },
      storageList: [],
      storageData: [] // 仓库数据
    };
  },
  mounted() {
    console.log('cgrk_part_search mounted');
    window.cgrk_part_search = this;
    // this.querySysTex();
    // this.getBrand();
    this.querySorageByType();
    this.list.find(item => item.fieldName == 'partType').itemList = this.createDictList('5000');
    this.columns.find(item => item.dataIndex == 'PART_TYPE').dictItems = this.createDictList('5000');
    this.columns.find(item => item.dataIndex == 'PART_TYPE').filterItems = this.createDictList('5000');
    // this.findAllRepair();
  },
  methods: {
    handleTableRowSelectChange(e) {
      this.onChangeColumn = e;
      // this.onEnterEvent(e[0]);
    },
    // 获取税率
    async querySysTex() {
      let res = await queryTex();
      this.tax = res.data;
      this.cunTax = res.data;
      // this.list.find(item => item.fieldName == 'tax').initialValue = res.data;
    },
    async findAllRepair() {
      const res = await findAllRepair();
      this.list.find(x => x.fieldName === 'storageCode').initialValue = res.data['1100'];
    },
    syncDataChange(val) {
      this.styleList = [];
      val.forEach(x => {
        if (x.PART_STATUS == '10041001') {
          this.styleList.push({ row: x, styles: { backgroundColor: '#FBE1E3' } });
        }
      });
    },
    async queryPartInfo(params) {
      console.log(params, 'params');
      // const res = await axios.get(`${SERVER.DMSCLOUD_PART}/basedata/ttRepairOrder/queryPartInfo`,{params}) //旧
      const res = await axios.get(`${SERVER.DMSCLOUD_PART}/stockmanage/partbuy/findPartForAdd`, { params }); // 新
      if (res.data.rows.length == 0 && this.pj) {
        this.$confirm('没有此配件，继续新增此配件吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            // params.PART_NO
            this.$emit('pdPartNo', params.partNo, params.storageCode);
            this.pj = false;
          })
          .catch(() => {
            this.pj = false;
            this.$emit('falsePartNo');
          });
      } else {
        this.pj = false;
        this.$emit('falsePartNo');
      }
      return res;
    },
    createList() {
      return [
        {
          type: 'SELECT',
          label: '仓库名称',
          fieldName: 'storageCode',
          itemList: []
          // rules: [{ required: true, message: '此字段为必填字段', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '配件属性',
          fieldName: 'partType',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName'
        },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'storagePositionCode'
        }
        // {
        //   type: 'INPUT',
        //   label: '车型组',
        //   fieldName: 'partModelGroupCodeSet'
        // },
        // {
        //   type: 'INPUT',
        //   label: '备注',
        //   fieldName: 'remark'
        // }
      ];
    },
    createColumns() {
      return [
        // 序号
        {
          title: '序号',
          width: 70,
          dataIndex: 'xuhao',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          },
          sorter: true
        },
        // 仓库
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          filter: true,
          filterType: 'input'
        },
        // 库位
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          filter: true,
          filterType: 'input'
        },
        // 配件代码
        {
          title: '配件代码',
          width: 100,
          showOverflowTooltip: true,
          dataIndex: 'PART_NO',
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件属性',
          width: 100,
          showOverflowTooltip: true,
          dataIndex: 'PART_TYPE',
          filter: true,
          dictItems: [],
          filterItems: [],
          filterKey: 'PART_TYPE',
          filterType: 'checkbox'
        },
        // 配件名称
        {
          title: '配件名称',
          width: 100,
          showOverflowTooltip: true,
          dataIndex: 'PART_NAME',
          filter: true,
          filterType: 'input'
        },
        {
          title: '入库数量',
          sorter: true,
          dataIndex: 'IN_QUANTITY',
          precision: 2,
          filter: true,
          filterType: 'number',
          min: 0,
          max: Infinity,
          widht: 130,
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        // 账面库存
        {
          title: '账面库存',
          sorter: true,
          dataIndex: 'STOCK_QUANTITY',
          filter: true,
          filterType: 'number',
          precision: 2
        },
        // 借进数量
        // {
        //   title: '借进数量',
        //   // sorter: true,
        //   dataIndex: 'BORROW_QUANTITY'
        // },
        // 借出数量
        // {
        //   title: '借出数量',
        //   // sorter: true,
        //   dataIndex: 'LEND_QUANTITY'
        // },
        // 备注
        {
          title: '厂家建议零售价',
          sorter: true,
          dataIndex: 'INSTRUCT_PRICE',
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '最新进货价',
          sorter: true,
          dataIndex: 'LATEST_PRICE',
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          filter: true,
          filterType: 'input'
        }
      ];
    },

    // 计算table中数据（含税价格等）
    computedTableData(newVal) {
      let tax = this.tax;
      newVal.map(item => {
        let inCount = item.IN_QUANTITY * 1;
        // item.IN_PRICE_TAXED = item.IN_PRICE_TAXED || item.IN_PRICE * (1 + tax * 1);
        // item.IN_PRICE = item.IN_PRICE_TAXED / (1 + tax * 1);
        item.IN_PRICE_TAXED = item.IN_PRICE * (1 + tax * 1);
        item.IN_AMOUNT = (item.IN_PRICE * inCount).toFixed(2);
        item.IN_AMOUNT_TAXED = (item.IN_PRICE_TAXED * inCount).toFixed(2);
      });
    },
    cellChangeHanle(key, row) {
      console.log(111, this.tax, '税率', 111);

      let keys = Object.keys(key);
      let ket = keys[0];
      let editKey = ket.substring(ket.indexOf('|') + 1);
      console.log('editKey', editKey);
      // - * / 会做隐式转换所以不用parseFloat
      // 数量改变时
      if (editKey == 'IN_QUANTITY') {
        // IN_AMOUNT (不含税金额 = 数量 *不含税单价)
        row.IN_AMOUNT = ((row.IN_QUANTITY || 0) * (row.IN_PRICE || 0)).toFixed(2);
        // IN_AMOUNT_TAXED(含税金额 = 数量 *含税单价)
        row.IN_AMOUNT_TAXED = ((row.IN_QUANTITY || 0) * (row.IN_PRICE_TAXED || 0)).toFixed(2);
      }
      // 不含税单价改变时
      if (editKey == 'IN_PRICE') {
        // IN_AMOUNT (不含税金额 = 数量 *不含税单价)
        row.IN_AMOUNT = ((row.IN_QUANTITY || 0) * (row.IN_PRICE || 0)).toFixed(2);
        // IN_AMOUNT_TAXED(含税单价 = 不含税单价 *（ 1 + 税率 ）)
        row.IN_PRICE_TAXED = ((row.IN_PRICE || 0) * (1 + Number(this.tax))).toFixed(2);
        // IN_AMOUNT_TAXED(含税金额 = 数量 * 含税单价)
        row.IN_AMOUNT_TAXED = ((row.IN_QUANTITY || 0) * (row.IN_PRICE_TAXED || 0)).toFixed(2);
      }
      // 含税单价改变时
      if (editKey == 'IN_PRICE_TAXED') {
        // IN_PRICE( 不含税单价= 含税单价 /（ 1 + 税率 ）)
        row.IN_PRICE = ((row.IN_PRICE_TAXED || 0) / (1 + Number(this.tax))).toFixed(2);
        // IN_AMOUNT (不含税金额 = 数量 *不含税单价)
        row.IN_AMOUNT = ((row.IN_QUANTITY || 0) * (row.IN_PRICE || 0)).toFixed(2);
        // IN_AMOUNT_TAXED(含税金额 = 数量 * 含税单价)
        row.IN_AMOUNT_TAXED = ((row.IN_QUANTITY || 0) * (row.IN_PRICE_TAXED || 0)).toFixed(2);
      }
    },
    // 品牌下拉框获取
    async getBrand() {
      const res = await getBrand();
      this.list.find(x => x.fieldName === 'brand').itemList = res.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_CODE + '' }));
    },
    // 获取仓库列表
    async querySorageByType() {
      let res = await getCangKuSelect({
        type: 1 // 0是非oem 0是oem  EP-23605 去除入库oem类型限制
        // ptype: this.ptype ? this.ptype : null // ,模块区分
      });
      let storageData = res.data.map(item => ({ text: item.STORAGE_NAME, value: item.STORAGE_CODE }));
      this.storageData = storageData;
      this.storageList = res.data;
      this.list.find(x => x.fieldName === 'storageCode').itemList = storageData;
    },
    formChange(p) {
      console.log('formChange', p);
      let params = JSON.parse(JSON.stringify(p));
      this.pj == !!params.partNo;
      !params.storageCode ? (params.storageCodeItem = this.storageData.map(item => item.value).join(',')) : '';
      this.fetchParams.xhrAbort = true;
      params.isAll = 'yes';
      // this.fetchParams = Object.assign(params, { xhrAbort: false, oemTag: this.type == 'add' ? 0 : 1, ptype: this.ptype ? this.ptype : null });  EP-23605 去除入库oem类型限制
      this.fetchParams = Object.assign(params, { xhrAbort: false, ptype: this.ptype ? this.ptype : null });
    },
    onPageChange() {
      console.log('onPageChange');
    },
    async onEnterEvent(row) {
      // 双击选中  整合配件信息
      console.log('onEnterEvent', row);
      if (row.PART_STATUS == '10041001') {
        this.$notify({
          title: '警告',
          message: '配件已停用',
          type: 'warning'
        });
        return;
      }
      let storageType = this.storageList.find(x => x.STORAGE_CODE == row.STORAGE_CODE).STORAGE_TYPE;
      row.STORAGE_TYPE = storageType;
      console.log('onEnterEventAfter', row);
      this.$emit('dblclickPartInfo', Object.assign({}, row));
      return;
    }
  }
};
</script>

<style></style>
